// pages/calling/result.js
var config = require('../../config.js');
var amapFile = require('../../libs/amap-wx.js');
var util = require('../../network_util.js');
var commonjs = require('../../common.js');
var app = getApp();

var mapCtx;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //司机信息为获取失败时，显示默认资料
    driverName:"司机",   //司机姓名
    brandName:"未知车型", //车的品牌
    platenumber:"0000000", //车牌
    picture:"../../images/niming.jpg", //匿名头像图片
    starlevel:0, //星级
//----------------------------------
    windowHieght: 1206,
    mapHeight: 744,
    infoHeight: 670,
    latitude: 0,
    longitude: 0,
    scale: 10,
    orderStatus: 0, //0-没有车，1-预约成功等待接单，2-已安排出行管家， 3-已安排司机，4-司机已经在等候，5-已经开始行程，6-行程结束，待支付， 6-已支付，待评价， 7-已评价
    driverPosition: 0,
    orderId: 0,
    userInfo: {},
    currentOrder: {}, //当前订单
    orderInfoTmp: {}, //订单集合列表
    second: 1,
    waitingMax: 180,
    countStop: false,
    onCounting: false,
    stopRolling: true,
    guiderInfo: {},
    driverInfo: {},
    orderDetail: {},
    commentInfo: {},
    commentTags: [],
    payInfo: {},
    couponList: {},
    discountId: 0,
    unionOrderInfo: {},
    openId: "",
    helpUrl: "http://yunsan.jlkfapp.com/help_guide/view/index.html",
    priceMode: 1, //1-套餐， 2-普通，3-一口价
    markers: [{
      iconPath: "../../images/icon_star@2x.png",
      id: 0,
      latitude: 23.099994,
      longitude: 113.324520,
      width: 44,
      height: 66
    }, {
      iconPath: "../../images/icon_end@2x.png",
      id: 1,
      latitude: 23.099994,
      longitude: 113.334520,
      width: 44,
      height: 66
    }],
    polyline: [{
      points: [{
        longitude: 113.3245211,
        latitude: 23.10229
      }, {
        longitude: 113.324520,
        latitude: 23.21229
      }],
      color: "#FF0000DD",
      width: 2,
      dottedLine: true
    }],
    controls: []
  },
  regionchange(e) {
    console.log(e.type)
  },
  markertap(e) {
    console.log(e.markerId)
  },
  controltap(e) {
    console.log(e.controlId)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ stopRolling: false });
    this.setData({ windowHeight: parseInt(wx.getStorageSync("systemInfo").windowHeight) * 2 })
    var that = this;
    //获取用户信息
    this.setData({ userInfo: wx.getStorageSync("userInfo") });
    var openId = wx.getStorageSync("openId");
    wx.getStorage({
      key: 'openId',
      success: function (res) {
        console.log("order.wx.getstorage = " + res);
        that.setData({ openId: openId });
      }
    })

    console.log("openId = " + this.data.openId);
    wx.getLocation({
      success: function (res) {
        cosnole.log(res,"++++++++++++++++")
        that.setData({ latitude: res.latitude, longitude: res.longitude })
      },
    })

    this.setData({ orderId: options.orderId });
    // console.log("orderInfoTmp: ");
    // console.log(wx.getStorageSync("orderInfoTmp"));
    // var orderInfoTmpStr = wx.getStorageSync("orderInfoTmp");
    // if (orderInfoTmpStr != null && orderInfoTmpStr != "") {
    //   var orderInfoTmp = JSON.parse(orderInfoTmpStr);
    //   console.log(orderInfoTmp);
    //   console.log(orderInfoTmp.length);
    //   for (var i = 0; i < orderInfoTmp.length; i++) {
    //     console.log(orderInfoTmp[i].orderId);
    //     console.log(this.data.orderId);
    //     if (orderInfoTmp[i].orderId == this.data.orderId) {
    //       this.setData({ "currentOrder": orderInfoTmp[i] });
    //       break;
    //     }
    //   }
    //   console.log("currentOrder: ");
    //   console.log(this.data.currentOrder);
    // }
    this.getOrderDetail();
    //每秒轮训一次订单状态
    this.orderRolling(this);
  },
  getOrderStatus: function () {
    console.log("begin getOrderStatus...");
    var that = this;
    //获取订单状态
    util._get(config.reservation + "?orderId=" + that.data.orderId,
      function (res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            that.setData({ countStop: true });
            that.setData({ orderStatus: res.data.data.queryStatus });
            that.setData({ driverPosition: res.data.data.driverPosition });
            // that.setData({mapHeight: 1044})
            // that.setData({ infoHeight: 270 });
            // that.setData({ mapHeight: that.data.windowHeight - that.data.infoHeight });
            if (that.data.orderStatus == 9) {//待支付，获取支付信息
              // that.setData({ infoHeight: 670 });
              wx.setNavigationBarTitle({ title: '支付' })

            // that.setData({ infoHeight: 670 });
              console.log("that.data.windowHeight=" + that.data.windowHeight);
              console.log("that.data.infoHeight=" + that.data.infoHeight);
              that.setData({ mapHeight: that.data.windowHeight - that.data.infoHeight });
              console.log("that.data.mapHeight=" + that.data.mapHeight);
              that.includePoints(); //缩小地图
              util._get(config.getPayInfo
                + "?orderId=" + that.data.orderId
                + "&userId=" + that.data.userInfo.id
                , function (res) {
                  // console.log(res);
                  if (res.statusCode == 200) {
                    if (res.data.code == 200) {
                      console.log(res.data.data[0], "------11------")
                      that.setData({ payInfo: res.data.data[0] });
                      that.setData({ payMode: res.data.data[0].calType });

                      //获取优惠券信息
                      util._get(config.myCouponList
                        + "?money=" + that.data.payInfo.totalMoney
                        + "&userId=" + that.data.userInfo.id
                        , function (res) {
                          // console.log(res);
                          if (res.statusCode == 200) {
                            if (res.data.code == 200) {
                              that.setData({ couponList: res.data.data[0] });
                            } else if (res.data.code == 0) {
                              //没有可用优惠券
                              that.setData({ couponList: '' });
                            } else {
                              // wx.showToast({
                              //   title: '1获取可用优惠券列表出错(' + res.data.code + ')',
                              // })
                            }
                          } else {
                            //网络错误
                            wx.showToast({
                              title: '获取可用优惠券列表发生系统错误(' + res.statusCode + ')',
                            
                            })
                          }
                        })

                    } else {
                      wx.showToast({
                        title: '获取支付信息出错(' + res.data.code + ')',
                     
                      })
                    }
                  } else {
                    //网络错误
                    wx.showToast({
                      title: '获取支付信息发生系统错误(' + res.statusCode + ')',
                    })
                  }
                })
            } else if (that.data.orderStatus == 1) {
              that.setData({ countStop: false });
              //数秒到120
              if (!that.data.onCounting) {
                //从缓存里读取已数秒数
                console.log("wx.getStorageSync._second=" + wx.getStorageSync(that.data.orderId + "_second"));
                var second = parseInt(wx.getStorageSync(that.data.orderId + "_second"));
                second = isNaN(second) ? 1 : second;
                that.setData({ second: second });
                that.countUp(that);
                // that.setData({ infoHeight: 270});
               
                // that.setData({ mapHeight: that.data.windowHeight - that.data.infoHeight });
              }
            } else if (that.data.orderStatus == 2) {
              // that.setData({ infoHeight: 270 });
              
              // that.setData({ mapHeight: that.data.windowHeight - that.data.infoHeight });
            } else if (that.data.orderStatus == 3) {
            // that.setData({ infoHeight: 270 });
          
            // that.setData({ mapHeight: that.data.windowHeight - that.data.infoHeight });
              //获取出行管家信息
              that.getGuiderInfo();
            } else if (that.data.orderStatus == 4
              || that.data.orderStatus == 5 //司机已出发
              || that.data.orderStatus == 6  //司机到达乘客出发点
              || that.data.orderStatus == 7  //乘客上车，开始行程
              || that.data.orderStatus == 8  //行程中
              || that.data.orderStatus == 10  //已完成 未评价
              || that.data.orderStatus == 11  //已完成 已评价
              || that.data.orderStatus == 16) {
              if (that.data.orderStatus == 10 || that.data.orderStatus == 11) {
                wx.setNavigationBarTitle({ title: '行程结束' })
                that.getOrderDetail();//更新订单价格
                // that.setData({ infoHeight: 470 });
                // that.setData({ mapHeight: that.data.windowHeight - that.data.infoHeight });

              }
              if (that.data.orderStatus == 11) { //获取已评价的信息
                that.getCommentInfo();
              }
              //获取司机信息
              that.getDriverInfo();
              // if (that.data.driverPosition != 0) {
              //   var currentOrder = that.data.currentOrder;
              //   var latitude = that.data.driverPosition.split(',')[1];
              //   var longitude = that.data.driverPosition.split(',')[0];
              //   var driverMarker = {
              //     height: 20,
              //     iconPath: "../../images/driverAvatar@2x.png",
              //     id: 2,
              //     latitude: latitude,
              //     longitude: longitude,
              //     width: 20
              //   }
              //   //删除已有的司机坐标
              //   for (var i = 0; i < currentOrder.markers.length; i++) {
              //     if (currentOrder.markers[i].id == 2) {
              //       currentOrder.markers.splice(i, 1);
              //     }
              //   }
              //   //添加新的司机坐标
              //   currentOrder.markers.push(driverMarker);
              //   that.setData({ currentOrder: currentOrder });
              // }
              console.log(that.data.currentOrder);
            }
          } else {
            //获取订单状态出错
          }
        }
      }, function (res) {
        console.log("getOrderStatus fail: ")
        console.error(res);
      })
  },
  getCommentInfo: function () {
    var that = this;
    util._get(config.orderCommentMessage + "?orderId=" + this.data.orderId + "&userId=" + this.data.userInfo.id,
      function (res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            that.setData({ commentInfo: res.data.data.comment });
            if (commonjs.isEmpty(res.data.data.comment.driverDetails)) {
              that.setData({ commentTags: [] })
            } else {
              that.setData({ commentTags: commonjs.trim(res.data.data.comment.driverDetails).split(',') });
            }
         }// else {
          //   wx.showToast({
          //     title: '获取评价信息出错(' + res.data.code + ')',
          //     duration: 5000   //设置的延迟时间
          //   })
          // }
        } else {
          //网络错误
          wx.showToast({
            title: '获取评价信息发生系统错误(' + res.statusCode + ')',
            duration: 5000
          })
        }
      })
  },
  getGuiderInfo: function () {
    var that = this;
    util._get(config.getGuideInfo + "?orderId=" + this.data.orderId + "&userId=" + this.data.userInfo.id,
      function (res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            that.setData({ guiderInfo: res.data.data });
          } else {
            wx.showToast({
              title: '获取出行管家信息出错(' + res.data.code + ')',
             
            })
          }
        } else {
          //网络错误
          wx.showToast({
            title: '获取出行管家信息发生系统错误(' + res.statusCode + ')',
          })
        }
      })
  },
  getDriverInfo: function () {
    var that = this;
    util._get(config.getDrivernfo + "?orderId=" + this.data.orderId + "&userId=" + this.data.userInfo.id,
      function (res) {
        if (res.statusCode == 200) {
        
          if (res.data.code == 200) {
            that.setData({ driverInfo: res.data.data });
            console.log(res.data.data)
          } else {
            wx.showToast({
              title: '获取司机信息出错(' + res.data.code + ')',
              duration: 5000
            })
          }
        } //else {
        //   //网络错误
        //   wx.showToast({
        //     title: '获取司机信息发生系统错误(' + res.statusCode + ')',
        //     duration: 5000
        //   })
        // }
      })
  },
  getOrderDetail: function () {
    var that = this;
    util._get(config.orderDetail + "?orderId=" + this.data.orderId,
      function (res) {
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            that.setData({ orderDetail: res.data.data });

            console.log("orderDetail: ");
            console.log(that.data.orderDetail);

            var currentOrder = {
              orderId: that.data.orderId,
              markers: [{
                iconPath: "../../images/icon_star@2x.png",
                id: 0,
                longitude: that.data.orderDetail.departurePosition.split(',')[0],
                latitude: that.data.orderDetail.departurePosition.split(',')[1],
                width: 20,
                height: 30
              }, {
                iconPath: "../../images/icon_end@2x.png",
                id: 1,
                longitude: that.data.orderDetail.arrivedPosition.split(',')[0],
                latitude: that.data.orderDetail.arrivedPosition.split(',')[1],
                width: 20,
                height: 30
              }]
            };
            that.setData({ currentOrder: currentOrder });
            that.includePoints();
          } else {
            wx.showToast({
              title: '获取订单信息出错(' + res.data.code + ')',
            })
          }
        } else {
          //网络错误
          wx.showToast({
            title: '获取订单信息发生系统错误(' + res.statusCode + ')',
          })
        }
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.mapCtx = wx.createMapContext('map');
    this.includePoints();
  },
  includePoints: function () { //将所有坐标点显示出来
    this.mapCtx.includePoints({
      padding: [10],
      points: this.data.currentOrder.markers
    })
  },

  countUp: function (that) {
    console.log("countUp: " + that.data.second);
    that.setData({ onCounting: true });
    if (!that.data.countStop) {
      var second = that.data.second
      if (second == that.data.waitingMax) {
        wx.setStorageSync(that.data.orderId + "_second", 0);
        wx.showModal({
          title: '暂时没有可服务车辆',
          content: '请稍后再试',
          confirmText: "确定",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              //调用取消订单接口
              that.cancelOrder(1);
            }
          }
        })
        return;
      }

      var time = setTimeout(function () {
        // console.log(that.data.second);
        if (that.data.second < that.data.waitingMax) {
          that.setData({
            second: second + 1
          });
          wx.setStorageSync(that.data.orderId + "_second", second);
        }
        that.countUp(that);
      }
        , 1000)
    }
  },
  orderRolling: function (that) {
    var time = setTimeout(function () {
      // console.log(that.data.second);
      // if (that.data.second < that.data.waitingMax) {
      //   that.setData({
      //     second: second + 1
      //   });
      // }
      if (!that.data.stopRolling) {
        that.getOrderStatus();
        that.orderRolling(that);
      }
    }
      , 1000)
  },
  cancelOrder: function (tp) {
    var that = this;
    util._get(config.deleteOrder + "?userId=" + this.data.userInfo.id
      + "&orderId=" + this.data.orderId + "&type=" + tp
      , function (res) {
        that.setData({ countStop: true });
        //跳转回首页
        console.log("调用取消订单接口成功");
        wx.redirectTo({
          url: '/pages/placing/pickup',
        })
      }, function (res) {
        //跳转回首页
        console.log("调用取消订单接口失败");
        wx.redirectTo({
          url: '/pages/placing/pickup',
        })

      })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({ stopRolling: false });
    this.orderRolling(this);//继续轮询
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({ stopRolling: true });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({ stopRolling: true });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onPhone: function (e) {
    console.log("onPhone in...");
    console.log(e);
    wx.makePhoneCall({
      phoneNumber:e.currentTarget.dataset.phone, // e.currentTarget.dataset.phone,
      success: function (suc) {
        console.log(suc);
      },
      fail: function (err) {
        console.log(err);
      }
    })
  },
  onCancel: function () {
    var that = this;
    wx.showModal({
      title: '确定要取消此订单',
      // content: '确定退出账号 ' + this.data.userInfo.name + ' 吗？',
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          console.log("user tap confirm");
          that.cancelOrder(2); //人为取消
          // wx.removeStorageSync("userInfo");
          // wx.redirectTo({
          //   url: 'pickup',
          // })
        } else if (res.cancel) {
          console.log("user tap cancel");
          this.cancleOrder(2);
        }
      }
    })
  },
  onStarTap: function () {
    wx.navigateTo({
      url: '/pages/placing/rating?orderId=' + this.data.orderId
    })
  },
  onPay: function () {
    //先停止轮询
    this.setData({ stopRolling: true });
    //调用后台支付进行统一下单
    var that = this;

    util._get(config.orderPay 
    + "?type=3&driverOrUser=1&money=" 
    + "0.01"  
    // + this.data.payInfo.totalFee 
    + "&orderNo=" + this.data.orderId + "&discountId=" + this.data.discountId + "&openId=" + this.data.openId 
      , function (res) {
        console.log("统一下单返回：");
        console.log(res);
        if (res.statusCode == 200) {
          if (res.data.code == 200) {
            var unionOrderInfo = res.data.data;
            that.setData({ unionOrderInfo: unionOrderInfo });
            //拿到统一下单数据调用微信接口进行支付
            wx.requestPayment({
              timeStamp: unionOrderInfo.timeStamp,
              nonceStr: unionOrderInfo.nonceStr,
              package: unionOrderInfo.packageValue,
              signType: 'MD5',
              paySign: unionOrderInfo.paySign,
              success: function (res) {
                console.log(res);
              },
              fail: function (res) {
                console.log(res);
              },
              complete: function (res) {
                console.log(res);
                //继续轮询
                that.setData({ stopRolling: false });
                that.orderRolling(that);//继续轮询
              }
            })
          } else {
            wx.showToast({
              title: '统一下单出错(' + res.data.code + ')',
            })
          }
        } else {
          //网络错误
          wx.showToast({
            title: '统一下单发生系统错误(' + res.statusCode + ')',
          })
        }
      });
  }
})